import mysql from "mysql2";

// 连接池单例
let pool: mysql.Pool | null = null;

// 获取数据库连接池（单例模式）
export const getDB = () => {
  // 如果连接池已存在，直接返回
  if (pool) {
    return pool.promise();
  }
  
  const config = useRuntimeConfig();
  
  // 创建新的连接池
  pool = mysql.createPool({
    host: config.DB_HOST,
    user: config.DB_USER,
    database: config.DB_DATABASE,
    password: config.DB_PASSWORD,
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0,
    // 添加连接错误处理
    enableKeepAlive: true,
    keepAliveInitialDelay: 0,
  });
  
  // 监听连接错误
  pool.on('error', (err) => {
    console.error('数据库连接池错误:', err);
    // 如果是致命错误，重置连接池
    if (err.code === 'PROTOCOL_CONNECTION_LOST' || err.code === 'ECONNRESET') {
      pool = null;
    }
  });
  
  return pool.promise();
};
